<template>
  <div class="announcement-management">
    <!-- 搜索区域 -->
    <div class="action-bar">
      <div class="search-area">
        <el-input
            v-model="searchTitle"
            placeholder="输入公告标题搜索"
            class="search-input"
        />
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </div>

    <!-- 公告表格 -->
    <el-table :data="paginatedAnnouncements" style="width: 100%">
      <el-table-column prop="id" label="公告编号" width="100" />
      <el-table-column prop="title" label="公告标题" />
      <el-table-column prop="publishTime" label="发布时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '生效中' ? 'success' : 'info'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="handleViewDetails(scope.row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:currentPage="currentPage"
          :page-size="pageSize"
          :total="totalAnnouncements"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useUserStore } from "../../../../stores/user.ts";
import {
  ClubAnnouncementControllerService,
  type ClubAnnouncementQueryRequest,
  type ClubAnnouncementVO,
} from "../../../../../generated";
import {useRoute, useRouter} from "vue-router";

interface ShowedAnnouncement {
  id: number;
  title: string;
  publishTime: string;
  status: string;
}

const store = useUserStore();
const route = useRoute();
const clubId = Number(route.query.clubId);

const announcements = ref<ShowedAnnouncement[]>([]);
const clubAnnouncementQueryRequest = ref<ClubAnnouncementQueryRequest>({
  pageSize: 10,
  current: 1,
  clubId: clubId,
});

const searchTitle = ref("");
const currentPage = ref(1);
const pageSize = ref(10);

// 计算总公告数
const totalAnnouncements = computed(() => announcements.value?.length || 0);

// 计算当前页的公告列表
const paginatedAnnouncements = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return announcements.value?.slice(startIndex, endIndex) || [];
});

const loadData = async () => {
  try {
    const res = await ClubAnnouncementControllerService.listClubAnnouncement(
        clubAnnouncementQueryRequest.value,
    );
    if (res.code === 0 && res.data?.records) {
      const announcementVoList = res.data.records as ClubAnnouncementVO[];
      announcements.value = announcementVoList.map((announcementVo) => ({
        id: announcementVo.id,
        title: announcementVo.title,
        publishTime: announcementVo.createTime,
        status: announcementVo.isDelete,
      }));
    } else {
      announcements.value = [];
      ElMessage.error("加载数据失败：" + (res.message || "未知错误"));
    }
  } catch (error) {
    console.error("加载数据时发生错误:", error);
    ElMessage.error("加载数据时发生错误，请稍后重试");
    announcements.value = [];
  }
};

onMounted(() => {
  loadData();
});

// 搜索方法
const handleSearch = () => {
  clubAnnouncementQueryRequest.value.title = searchTitle.value;
  clubAnnouncementQueryRequest.value.current = 1;
  currentPage.value = 1;
  loadData();
};

const router = useRouter();

// 查看详情方法
const handleViewDetails = (announcement: ShowedAnnouncement) => {
  router.push({
    path: "/club/announcement/info",
    query: { id: announcement.id, clubId: clubId },
  });
};

// 页码变化处理方法
const handlePageChange = (page: number) => {
  currentPage.value = page;
};
</script>

<style scoped>
.announcement-management {
  padding: 20px;
  background: white;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
